const Koa = require('koa');
const Router = require('koa-router');
const render = require('koa-swig');
const fs = require("fs");
const path = require("path");
const { reslove,join } = require('path');
const co = require('co');

const app = new Koa();
const router = new Router();

app.context.render = co.wrap(
    render({
        root:join(__dirname,'views'),
        autoescape:true,
        //ssr最关键的地方
        cache:false,
        ext:'html',
        writeBody:false
    })
)

const task1 = () =>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(`<script>addHTML("part1","我是第一次的输出<br/>")</script>`);
        },2000)
    })
}

const task2 = () =>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(`<script>addHTML("part2","我是第二次的输出<br/>")</script>`);
        },2000)
    })
}
router.get('/real',async(ctx,next)=>{
    ctx.status = 200;
    ctx.type = 'html';
    const file = fs.readFileSync("./views/index.html",'utf8');
    ctx.res.write(file);
    const result1 = await task1();
    ctx.res.write(result1);
    const result2 = await task2();
    ctx.res.write(result2);
    ctx.res.end();
})
router.get("/",async(ctx,next)=>{
    //自己修正请求头
    ctx.status = 200;
    ctx.type = 'html';
    const filename = path.join(__dirname,'/views/index.html');
    // --demo1 html已经通过预渲染的手段已经渲染完毕 ---
    // const filename = fs.readFileSync("./views/index.html","utf8");
    // ctx.res.write(filename);
    // ctx.res.end();
    // ---demo02 对上述情况的延续 ---
    // function createSsrStreamPromise(){
    //     return new Promise((resolve,reject)=>{
    //         const stream = fs.createReadStream(filename);
    //         stream.on('error',(err)=>{
    //             reject(err);
    //         }).pipe(ctx.res)
    //     })
    // }
    // await createSsrStreamPromise();
    // ctx.res.end();
    // --- demo3 对上述情况的延续 ---
    function createSsrStreamPromise(){
        return new Promise((resolve,reject)=>{
            const stream = fs.createReadStream(filename);
            stream.on('data',(chunk)=>{
                ctx.res.write(chunk);
            })
            stream.on('end',()=>{
                ctx.res.end();
            })
        })
    }
    await createSsrStreamPromise();
})
router.get('/index',async(ctx,next)=>{
    // 性能直出 (直接输出HTML) -> 用户请求过来
    ctx.body = await ctx.render('index');
})
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);